import axios from 'axios';
import { ElMessage } from 'element-plus'

const axiosjs = {
    needLoadingRequestCount: 0
}

//弹出错误提示
axiosjs.errorMessage = function (status) {
    let msg = "";
    switch (status) {
        case 400:
            msg = '请求参数错误'
            break
        case 401:
            msg = '未授权，请登录'
            break
        case 403:
            msg = '跨域拒绝访问'
            break
        case 404:
            msg = '请求地址出错'
            break
        case 408:
            msg = '请求超时'
            break
        case 500:
            msg = '服务器内部错误'
            break
        case 501:
            msg = '服务未实现'
            break
        case 502:
            msg = '网关错误'
            break
        case 503:
            msg = '服务不可用'
            break
        case 504:
            msg = '网关超时'
            break
        case 505:
            msg = 'HTTP版本不受支持'
            break
        default:
            msg = '请求错误'
            break
    }
    return msg;
}

//请求拦截
axios.interceptors.request.use(config => {
    //var isapi = config.url.indexOf("api") > -1;
    if (config.method === 'post') {
        config.headers['Content-Type'] = 'application/json';
        //业务请求API
        if (!window.chrome.webview) {
            //config.headers['Authorization'] = 'Bearer ' +  token;
            config.url = '/proxy'  + (config.url[0] == '/' ? '': '/') + config.url
        }
    }
    return config;
}, (error) => {
    return Promise.reject(error);
});

/****** respone拦截器==>对响应做处理 ******/
axios.interceptors.response.use(response => {
        return response;
    },
    error => {
        let flag = axiosjs.errorMessage(error.response.status);
        ElMessage.error('请求状态: ' + error.response.status + ' ' + flag + '\n错误信息: ' + error.response.statusText);
        return Promise.reject(error)
        
    }
);

/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function get(url, params = {}) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
                params: params
            })
            .then(response => {
                resolve(response.data);
            })
            .catch(err => {
                reject(err)
            })
    })
}


/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url, data = {}) {
    //清除左右空格
    for(var k in data)
        if(typeof(data[k]) == 'string'){
            data[k] = data[k].trim()
        }
        
    return new Promise((resolve, reject) => {
        axios.post(url, data)
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err)
            })
    })
}